import 'package:flutter_1/utils/db/DatabaseHelper.dart';

/// 向用户表插入数据
class Insertuser {
  static Future<String> generateCustomerCode() async {
    final db = await DatabaseHelper.getDatabase();

    // 查询现有最大 customer_code
    final List<Map<String, dynamic>> result = await db
        .rawQuery("SELECT MAX(customer_code) AS max_code FROM User_table");

    // 提取现有的最大 customer_code，确保不为 null
    String maxCode = result.isNotEmpty && result[0]['max_code'] != null
        ? result[0]['max_code']
        : '';

    // 如果没有记录，设置为 'CUST001'
    if (maxCode.isEmpty) {
      return 'CUST001';
    } else {
      // 提取数字部分并增加1
      int number = int.parse(maxCode.substring(4)) + 1;
      return 'CUST' + number.toString().padLeft(3, '0');
    }
  }

  static Future<int> insert(String username, String name, String password,
      String phone, String email) async {
    final db = await DatabaseHelper.getDatabase();

    // 检查是否已有相同的 username
    final List<Map<String, dynamic>> existingUser = await db
        .rawQuery("SELECT * FROM User_table WHERE username = ?", [username]);

    if (existingUser.isNotEmpty) {
      throw Exception("Username already exists");
    }

    // 动态生成 customer_code
    String customerCode = await generateCustomerCode();

    // 构造插入的数据
    Map<String, dynamic> values = {
      'username': username,
      'customer_code': customerCode,
      'name': name,
      'password': password,
      'phone': phone,
      'email': email
    };

    // 执行插入操作
    return await DatabaseHelper.insert('User_table', values);
  }
}
